package org.seed.quantum.message.plugins;

import org.seed.quantum.memory.BufferPage;
import org.seed.quantum.memory.BufferPagePool;
import org.seed.quantum.socket.SocketServer;
import org.seed.quantum.util.QuickTimerTask;
import java.lang.reflect.Field;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class BufferPageMonitorPlugin <T> extends AbstractPlugin<T>{

    /**
     * 任务执行频率
     */
    private int seconds = 0;

    private SocketServer server;

    private ScheduledFuture<?> future;

    public BufferPageMonitorPlugin(SocketServer server, int seconds) {
        this.seconds = seconds;
        this.server = server;
        init();
    }

    private void init() {
        long mills = TimeUnit.SECONDS.toMillis(seconds);
        future = QuickTimerTask.scheduleAtFixedRate(() -> {
            {
                if (server == null) {
                    shutdown();
                    return;
                }
                try {
                    Field bufferPoolField = SocketServer.class.getDeclaredField("bufferPool");
                    bufferPoolField.setAccessible(true);
                    BufferPagePool pagePool = (BufferPagePool) bufferPoolField.get(server);
                    if (pagePool == null) {
                        shutdown();
                        return;
                    }
                    Field field = BufferPagePool.class.getDeclaredField("bufferPages");
                    field.setAccessible(true);
                    BufferPage[] pages = (BufferPage[]) field.get(pagePool);
                    String logger = "";
                    for (BufferPage page : pages) {
                        logger += "\r\n" + page.toString();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, mills, mills);
    }

    private void shutdown() {
        if (future != null) {
            future.cancel(true);
            future = null;
        }
    }
}
